package cn.gqr.service.impl;

import cn.gqr.entity.Largefile;
import cn.gqr.entity.Role;
import cn.gqr.entity.User;
import cn.gqr.mapper.PictureMapper;
import cn.gqr.mapper.UserMapper;
import cn.gqr.service.UserService;
import cn.gqr.tool.CacheService;
import cn.gqr.tool.Toolkit;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private CacheService cn;

    //用户注册
    @Transactional
    public boolean registerUser(User user) {
        user.setClosed(0);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //默认头像
        user.setImg("02ff76836ff44901bbeab20e87f14ddd");

        userMapper.insert(user);
        int i2 = userMapper.insertUserRole(user.getId());
        return i2>0;
    }

    //用户更新密码
    public boolean updateUserPassword(String password) {

        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper();

        lambdaUpdateWrapper
                .eq(User::getId, Toolkit.getUser().getId())
                .set(User::getPassword,passwordEncoder.encode(password));

        return update(lambdaUpdateWrapper) ;
    }

    //用户更新头像
    @Override
    @Transactional
    public String updateUserPicture(MultipartFile file) {

        //获取图片uuid并且添加图片到数据库
        Largefile largefile = null;
        try {

            largefile = Toolkit.filesUpload(new Largefile(), file);
            pictureMapper.insert(largefile);

        } catch (IOException e) {

            throw new RuntimeException(e.getMessage());
        }

        //把uuid赋值给用户头像字段
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper
                .eq(User::getId, Toolkit.getUser().getId())
                .set(User::getImg,largefile.getId());
        update(lambdaUpdateWrapper);

        //默认头像，不删除
        String imgId = Toolkit.getUser().getImg();

        if("02ff76836ff44901bbeab20e87f14ddd".equals(imgId)){
            return largefile.getId();
        }

        //删除原来的头像
        pictureMapper.deleteById(imgId);

        return largefile.getId();
    }

    //修改用户名称和电话
    public boolean updateNicknameOrPhone(String nickname, String phone) {
        int i = userMapper.updateNicknameOrPhone(nickname, phone, Toolkit.getUser().getId());
        return i>0;
    }

    //查找所有买家信息并且分页
    public Map queryAllUsers(int start, int num) {
        List<User> users = userMapper.queryAllUsers(start, num);
        Integer total = userMapper.queryAllUsersTotal();
        Map map = new HashMap();
        map.put("users",users);
        map.put("total",total);
        return map;
    }

    //注册管理员
    @Transactional
    public boolean registerAdmin(User user, MultipartFile file) {

        user.setClosed(0);

        user.setPassword(passwordEncoder.encode(user.getPassword()));

        //默认头像
        user.setImg("02ff76836ff44901bbeab20e87f14ddd");

        //上传文件不等空
        if(file != null){

            Largefile largefile = null;

            try {

                largefile = Toolkit.filesUpload(new Largefile(), file);

            } catch (IOException e) {

                throw new RuntimeException(e);
            }

            //上传头像
            pictureMapper.insert(largefile);

            user.setImg(largefile.getId());

        }


        userMapper.insert(user);

        int i = userMapper.insertAdminRole(user.getId());

        return i>0;
    }

    //买家账号解冻或者冻结
    public boolean unfreezeUserOrFrozenAccount(int uid,int closed) {

        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper();

        lambdaUpdateWrapper
                .eq(User::getId, uid)
                .set(User::getClosed,closed);

        return update(lambdaUpdateWrapper);
    }

    //根据买家id查询买家信息
    public User selectUserById(int id) {
        User user = userMapper.selectById(id);
        user.setPassword(null);

        return user;
    }



    //根据用户名称查询用户信息
    @Override
    public User selectUserByUsername(String username) {
        User user = userMapper.selectUserInfoByUsername(username);
//        cn.add(user.getId()+"",user);
//        Object o = cn.get(user.getId() + "");
//        System.out.println((User)o);
        return user;
    }

    //根据用户id查询用户角色
    @Override
    public List<Role> selectUserRole(Integer roleId) {
        return userMapper.selectUserRole(roleId);
    }

    //根据用户角色查询用户权限
    @Override
    public List<String> selectUserPermissions(Integer userId) {
        return userMapper.selectUserPermissions(userId);
    }


}
